package com.ljwy.daka;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatSpinner;

import com.ljwy.daka.adapter.CpSpinnerAdapter;
import com.ljwy.daka.info.CpInfo;
import com.ljwy.daka.okgoHelper.GsonConvert;
import com.ljwy.daka.okgoHelper.HttpRequestHelper;
import com.ljwy.daka.okgoHelper.JsonCallback;
import com.ljwy.daka.utils.cache.ACacheHelper;
import com.lzy.okgo.model.Response;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.ljwy.daka.utils.Constant.GET_CP_LIST;
import static com.ljwy.daka.utils.Constant.IP;

public class InputActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {

    @BindView(R.id.choose_tv)
    TextView chooseTv;
    @BindView(R.id.cp_spinner)
    AppCompatSpinner cpSpinner;
    private HashMap<String, String> hashMap;
    private CpInfo info;
    private CpInfo.DataBean dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input);
        ButterKnife.bind(this);
        hashMap = new HashMap<>();
        if (TextUtils.isEmpty(ACacheHelper.getInstance().getString("CPID", ""))) {
            getCp();
        } else {
            intent();
        }

    }

    private void getCp() {
        HttpRequestHelper.getRequest(mContext, IP + GET_CP_LIST, hashMap, new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                info = GsonConvert.fromJson(response.body(), CpInfo.class);
                CpSpinnerAdapter adapter = new CpSpinnerAdapter(mContext, info.getData());
                cpSpinner.setAdapter(adapter);
                cpSpinner.setOnItemSelectedListener(InputActivity.this);
            }
        });
    }

    @OnClick(R.id.confirm_btn)
    public void onViewClicked() {
        ACacheHelper.getInstance().putString("CPID", String.valueOf(dataBean.getCp_id()));
        ACacheHelper.getInstance().putString("CPNAME", String.valueOf(dataBean.getCp_name()));
        intent();
    }

    private void intent() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        dataBean = info.getData().get(i);
        chooseTv.setText(String.format("%s %s", "您选择的是：" + dataBean.getCp_name(), dataBean.getActivity_name()));
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}